﻿using System;
using System.Collections.Generic;
using System.Text;
using Castle.Windsor;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel;
using Castle.MicroKernel.SubSystems.Conversion;
using Castle.MicroKernel.Handlers;

namespace NGinnBPM.Engine.WindsorHost.Util
{
    public class HandlerForwardingFacility : AbstractFacility
    {

        IConversionManager conversionManager;

        protected override void Init()
        {
            conversionManager = (IConversionManager)Kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey);
            Kernel.HandlerRegistered += new HandlerDelegate(Kernel_HandlerRegistered);
        }

        void Kernel_HandlerRegistered(IHandler handler, ref bool stateChanged)
        {
            if (handler is ForwardingHandler) return;

            var model = handler.ComponentModel;

            if (model.Configuration == null) return;

            var forward = model.Configuration.Children["forward"];
            if (forward == null) return;

            foreach (var service in forward.Children)
            {
                Type forwardedType = (Type)conversionManager.PerformConversion(service, typeof(Type));
                Kernel.RegisterHandlerForwarding(forwardedType, model.Name);
            }
        }
    }
}
